package com.hzncc.scaffold.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.hzncc.scaffold.config.MinioConfig;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.QuestionBankCourseBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.*;
import com.hzncc.scaffold.mapper.CourseMapper;
import com.hzncc.scaffold.mapper.QuestionlibMapper;
import com.hzncc.scaffold.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 题库表 服务实现类
 * </p>
 *
 * @author DrunkBear
 * @since 2022-04-27
 */
@Service
public class QuestionlibServiceImpl extends ServiceImpl<QuestionlibMapper, Questionlib> implements QuestionlibService {

    @Autowired
    QuestionlibService questionlibService;

    @Autowired
    QuestionlibMapper questionlibMapper;

    @Autowired
    UserService userService;

    @Autowired
    QlibmajorService qlibmajorService;

    @Autowired
    MajorService majorService;

    @Autowired
    MinioConfig minioConfig;

    @Autowired
    CoursemajorService coursemajorService;


    @Autowired
    CourseMapper  courseMapper;

    @Autowired
    ChapterService chapterService;


    @Override
    public ResultT addQuestionLib(Questionlib questionlib) {
        boolean save = questionlibService.save(questionlib);
        if (save) {
            return ResultT.success("新增成功");
        } else {
            return ResultT.fail("新增失败");
        }
    }

    @Override
    public ResultT deleteQuestionLib(Integer questionLibId) {
        if (questionlibService.getById(questionLibId) != null) {
            Questionlib questionlib = questionlibService.getById(questionLibId);
            questionlib.setIsDelete(1);
            boolean update = questionlibService.updateById(questionlib);
            if (update) {
                return ResultT.success("删除成功");
            } else {
                return ResultT.fail("删除失败");
            }
        } else {
            return ResultT.fail("数据错误");
        }
    }

    @Override
    public ResultT updateQuestionLib(UpdateQuestionBankVo updateQuestionBankVo) {
        Questionlib questionlib = BeanUtil.toBean(updateQuestionBankVo, Questionlib.class);
        questionlib.setId(updateQuestionBankVo.getQuestionLibId());
        boolean update = questionlibService.updateById(questionlib);
        if (update) {
            return ResultT.success("修改成功");
        } else {
            return ResultT.fail("修改失败");
        }
    }

    @Override
    public ResultT search(Questionlib questionlib) {
        LambdaQueryWrapper<Questionlib> lqw = new LambdaQueryWrapper<>();
        lqw.eq(questionlib.getId() != null, Questionlib::getId, questionlib.getId());
        lqw.like(questionlib.getTitle() != null, Questionlib::getTitle, questionlib.getTitle());
        lqw.eq(questionlib.getOperatorId() != null, Questionlib::getOperatorId, questionlib.getOperatorId());
        lqw.eq(questionlib.getCreateTime() != null, Questionlib::getCreateTime, questionlib.getCreateTime());
        lqw.eq(questionlib.getIsDelete() != null, Questionlib::getIsDelete, questionlib.getIsDelete());

        List<Questionlib> questionlibList = questionlibService.list(lqw);
        return ResultT.success(questionlibList);
    }

    @Override
    public ResultT commit(CommitQuestionBankVo commitQuestionBankVo) {
        Questionlib questionlib = BeanUtil.toBean(commitQuestionBankVo, Questionlib.class);
        List<Integer> majorIdList = commitQuestionBankVo.getMajorId();
        questionlib.setOperatorId(StpUtil.getLoginIdAsInt());
        questionlib.setCreateTime(DateUtil.now());
        boolean save = questionlibService.save(questionlib);
        if (save) {
            QuestionLibIdVo questionLibIdVo = new QuestionLibIdVo();
            questionLibIdVo.setQuestionLibId(questionlib.getId());

            for (Integer majorId : majorIdList) {
                Qlibmajor qlibmajor = new Qlibmajor();
                qlibmajor.setMajorId(majorId);
                qlibmajor.setQuestionLibId(questionlib.getId());

                qlibmajorService.save(qlibmajor);
            }

            return ResultT.success(questionLibIdVo);
        } else {
            return ResultT.fail("新增失败");
        }
    }

    @Override
    public ResultT listQuestionLib(Integer pageNum, Integer pageSize, String keyword, Integer majorId) {
        ArrayList<QuestionBankVo> questionBankVos = new ArrayList<>();
        LambdaQueryWrapper<Questionlib> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Questionlib::getIsDelete, 0);
        lqw.eq(StrUtil.isNotEmpty(keyword), Questionlib::getTitle, keyword);

        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize * 2);
        }

        QueryWrapper<Questionlib> qw = new QueryWrapper<>();
        qw.eq("questionlib.isDelete", 0);
        if (majorId != null) {
            qw.eq("major.id", majorId);
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("questionlib.title", keyword);
        }
        qw.orderByDesc("questionlib.id");
        List<Questionlib> questionlibList = questionlibMapper.listQuestionLib(qw);

        for (Questionlib questionlib : questionlibList) {

            if (CollUtil.isNotEmpty(questionBankVos)) {
                List<QuestionBankVo> collect = questionBankVos.stream().filter(item -> item.getId().equals(questionlib.getId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(collect)) {
                    continue;
                }
            }
            QuestionBankVo questionBankVo = new QuestionBankVo();

            List<Question> questions = new ArrayList<>();

            List<Major> majors = new ArrayList<>();

            Operator operator = new Operator();

            Integer operationNum = 0;

            //题目总数
            Integer questionNum = 0;

            //单选题
            Integer singleNum = 0;

            //多选题
            Integer multiNum = 0;

            //判断题
            Integer judgeNum = 0;

            Integer questionlibId = questionlib.getId();

            QueryWrapper<QuestionBank> qww = new QueryWrapper<>();
            Integer id = questionlib.getId();
            qww.eq("questionlib.id", id);
            List<QuestionBank> questionBankList = questionlibMapper.list(qww);
            for (QuestionBank bank : questionBankList) {
                if (bank.getQuestionsType() != null) {
                    //如果题目为单选
                    if (bank.getQuestionsType() == 0) {
                        singleNum = singleNum + 1;
                    }
                    //如果题目为多选
                    if (bank.getQuestionsType() == 1) {
                        multiNum = multiNum + 1;
                    }
                    //如果题目为判断题
                    if (bank.getQuestionsType() == 2) {
                        judgeNum = judgeNum + 1;
                    }

                    Question question = new Question();
                    question.setId(bank.getQuestionsId());
                    question.setType(bank.getQuestionsType());
                    questions.add(question);
                }
            }
            questionNum = singleNum + multiNum + judgeNum;

            operator.setId(questionlib.getOperatorId());
            operator.setName(userService.getById(questionlib.getOperatorId()).getName());

            LambdaQueryWrapper<Qlibmajor> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Qlibmajor::getQuestionLibId, questionlib.getId());
            List<Qlibmajor> qlibmajorList = qlibmajorService.list(lqww);

            for (Qlibmajor qlibmajor : qlibmajorList) {
                Major major = majorService.getById(qlibmajor.getMajorId());
                majors.add(major);
            }


            qlibmajorService.list();

            questionBankVo.setId(questionlibId);
            questionBankVo.setTitle(questionlib.getTitle());
            questionBankVo.setOperator(operator);
            questionBankVo.setQuestions(questions);
            questionBankVo.setSingleNum(singleNum);
            questionBankVo.setMultiNum(multiNum);
            questionBankVo.setJudgeNum(judgeNum);
            questionBankVo.setQuestionNum(questionNum);
            questionBankVo.setMajors(majors);
            questionBankVo.setCreateTime(questionlib.getCreateTime());

            questionBankVos.add(questionBankVo);
        }
        PageInfo<QuestionBankVo> info = new PageInfo<>();
        info.setList(questionBankVos);

        QueryWrapper<Questionlib> qww = new QueryWrapper<>();
        qww.eq("questionlib.isDelete", 0);
        if (majorId != null) {
            qww.eq("major.id", majorId);
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("questionlib.title", keyword);
        }
        Integer total = questionlibMapper.selectTotal(qww);

        info.setTotal(total);

        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",questionBankVos);
        map.put("count",total);

        return ResultT.success(map);
    }

    @Value("${project.imgFileSuffix}")
    public String imgFileSuffix;
    @Autowired
    private TaskService taskService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private PaperService paperService;

    @Override
    public ResultT listQuestionLibPlus(Integer pageNum, Integer pageSize, Integer majorId, Integer isFree, String keyword, Integer isExercise) {
         if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            PageHelper.startPage(pageNum, pageSize);
        }

        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keyword)) {
            courseQueryWrapper.like("course.title", keyword);

        }
        if (isFree != null) {
            courseQueryWrapper.eq("course.isFree", isFree);
        }
        if (majorId != null) {
            courseQueryWrapper.eq("majors.pid", majorId);
        }
        courseQueryWrapper.eq(" course.status", 1);
        courseQueryWrapper.eq(" course.isDelete", 0);
        courseQueryWrapper.notIn("majors.pid",0);
        if(null != isExercise){
            courseQueryWrapper.eq(" course.isQuestionLibExercise", isExercise);
        }else {
            courseQueryWrapper.eq(" course.isQuestionLibExercise", 0);
        }
        List<Course> courses = courseMapper.listVo(courseQueryWrapper);
        List<Course> dataList = new ArrayList<>();
        if(CollUtil.isNotEmpty(courses)){
            for (Course cours : courses) {
                //处理数据
                LambdaQueryWrapper<Chapter> chapterQueryWrapper = new LambdaQueryWrapper<>();
                chapterQueryWrapper.eq(Chapter::getCourseId,cours.getId());
                chapterQueryWrapper.orderByDesc(Chapter::getCreateTime);
                List<Chapter> list = chapterService.list(chapterQueryWrapper);
                if(CollUtil.isNotEmpty(list)){
                    Chapter chapter = list.get(0);
                    LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    taskLambdaQueryWrapper.eq(Task::getChapterId,list.get(0).getId());
                    taskLambdaQueryWrapper.orderByDesc(Task::getCreateTime);
                    List<Task> taskList = taskService.list(taskLambdaQueryWrapper);
                    chapter.setTasks(taskList);
                    cours.setChapters(Arrays.asList(chapter));
                }
                if(StringUtil.isNotEmpty(cours.getCover())){
                    cours.setCover(imgFileSuffix+cours.getCover());
                }
                dataList.add(cours);
            }
            if(null != isExercise && isExercise == 1){
                for (Course cours : courses) {
                    List<Chapter> chapters = cours.getChapters();
                    if(CollUtil.isNotEmpty(chapters)){
                        List<Task> tasks = chapters.get(0).getTasks();
                        if(CollUtil.isNotEmpty(tasks)){
                            if(null != tasks.get(0).getQuestionLibId()){
                                Integer questionLibId = cours.getChapters().get(0).getTasks().get(0).getQuestionLibId();
                                LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(Question::getLibId,questionLibId);
                                queryWrapper.eq(Question::getType,0);
                                cours.setSingleCount(questionService.count(queryWrapper));
                                queryWrapper.eq(Question::getType,1);
                                cours.setMultiCount(questionService.count(queryWrapper));
                                queryWrapper.eq(Question::getType,2);
                                cours.setJudgeCount(questionService.count(queryWrapper));
                                queryWrapper.eq(Question::getType,3);
                                cours.setQuestionCount( questionService.count(queryWrapper));
                            }
                        }
                    }
                    dataList.add(cours);
                }
            }else if(null != isExercise && isExercise == 2){
                for (Course cours : courses) {
                    List<Chapter> chapters = cours.getChapters();
                    if(CollUtil.isNotEmpty(chapters)){
                        List<Task> tasks = chapters.get(0).getTasks();
                        if(CollUtil.isNotEmpty(tasks)){
                            Integer paperId = tasks.get(0).getPaperId();
                            Task task = tasks.get(0);
                            if(StringUtils.isNotEmpty(task.getExamStart())){
                                cours.setExamStart(task.getExamStart());
                            }
                            if(StringUtils.isNotEmpty(task.getExamEnd())){
                                cours.setExamEnd(task.getExamEnd());
                            }
                            Paper paper = paperService.getById(paperId);
                            if(BeanUtil.isNotEmpty(paper)){
                                cours.setExamTime(paper.getExamTime() != null?paper.getExamTime():0);
                                cours.setTotalScore(paper.getTotalScore() != null?paper.getTotalScore():0);
                                dataList.add(cours);
                            }
                        }

                    }

                }
            }
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",courses);
        map.put("count",new PageInfo<>(courses).getTotal());
        return ResultT.success(map);
    }

    @Override
    public ResultT detail(String questionLibld) {

        Integer questionLibId =Integer.parseInt(questionLibld);

        QueryWrapper<QuestionVo> qw = new QueryWrapper<>();
        if (questionLibId != null) {
            qw.eq("question.libId", questionLibId);
        }
        List<QuestionVo> questionList = questionlibMapper.detail(qw);

        String title = "";
        if (questionlibService.getById(questionLibId).getTitle() != null) {
            title = questionlibService.getById(questionLibId).getTitle();
        }
        for (QuestionVo questionVo : questionList) {
            Questionlib questionlib = new Questionlib();
            questionlib.setId(questionLibId);
            questionlib.setTitle(title);
            questionVo.setQuestionlib(questionlib);
        }

        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",questionList);
        map.put("count",questionList.size());

        return ResultT.success(map);
    }

}
